//
//  MEMyDataViewController.swift
//  aj
//
//  Created by leeqb on 15/11/27.
//  Copyright © 2015年 powerlee. All rights reserved.
//

import UIKit

var g_myDataVC: MEMyDataViewController!

class MEMyDataViewController: AJBaseTableViewController, UIAlertViewDelegate, PhotoPickerDelegate, DateSelectorDelegate {
    @IBOutlet weak var photoView: UIImageView!
    @IBOutlet weak var nickName: UILabel!
    @IBOutlet weak var trueName: UILabel!
    @IBOutlet weak var sex: UILabel!
    @IBOutlet weak var birthday: UILabel!
    @IBOutlet weak var address: UILabel!
    @IBOutlet weak var sign: UILabel!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        g_myDataVC = self
    }
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillDisappear(animated)
        
        // 显示头像
        self.photoView.sd_setImageWithURL(NSURL(string: userPhoto), placeholderImage: g_placeImage)
        //显示昵称
        self.nickName.text = userNickName
        //显示姓名
        self.trueName.text = userTrueName
        
        //显示性别
        let sex = userSex
        if sex == 0 {
            self.sex.text = "男"
        } else if (sex == 1) {
            self.sex.text = "女"
        } else {
            self.sex.text = "未设置"
        }
        
        //生日
        self.birthday.text = DataManager.userInfo()!["birthday"] as? String
        //地址
        self.address.text = DataManager.userInfo()!["address"] as? String
        //个性签名
        self.sign.text = DataManager.userInfo()!["sign"] as? String
    }
    
    // 保存用户资料
    func saveProfile(params: [NSObject : AnyObject], success:((responseObject: AnyObject!) -> Void), failed: ((error: NSError!) -> Void)) {
        CBMessage.shareInstance().showProcessing()
        AJNetworkHelper.instance.post("aj_user_mgr", parameters: params, success: { (operation: AFHTTPRequestOperation!, responseObject: AnyObject!) -> Void in
            success(responseObject: responseObject)
            }, failed: { (operation: AFHTTPRequestOperation!, error: NSError!) -> Void in
                failed(error: error)
            }) { () -> Void in
                CBMessage.shareInstance().dismiss()
        }
    }
    
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if segue.identifier == "segCitySelect" {
            //let vc = segue.destinationViewController as! MECitySelectTableViewController
        }
    }
    
    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        tableView.deselectRowAtIndexPath(indexPath, animated: false)
        
        switch indexPath.row {
        case 0:
            PhotoPicker.pick(self)
        case 1:
            let vc = LB("Common", vcName: "TextInputVC") as! TextInputViewController
            vc.title = "昵称"
            vc.text = userNickName
            vc.placeHolder = "请输入昵称"
            self.navigationController?.pushViewController(vc, animated: true)
            vc.completeBlock = {(text: String) -> Void in
                let params = ["nickName": text]
                g_myDataVC.saveProfile(params, success: { (responseObject) -> Void in
                    DataManager.updateLocalUserInfo("nickName", value: text)
                    self.nickName.text = userNickName
                    }) { (error) -> Void in
                }
            }
        case 2:
            let vc = LB("Common", vcName: "TextInputVC") as! TextInputViewController
            vc.title = "姓名"
            vc.text = userTrueName
            vc.placeHolder = "请输入姓名"
            self.navigationController?.pushViewController(vc, animated: true)
            vc.completeBlock = {(text: String) -> Void in
                let params = ["trueName": text]
                g_myDataVC.saveProfile(params, success: { (responseObject) -> Void in
                    DataManager.updateLocalUserInfo("trueName", value: text)
                    self.trueName.text = userTrueName
                    }) { (error) -> Void in
                }
            }
        case 3:
            let vc = LB("Me", vcName: "SexSelectVC") as! MESexViewController
            self.navigationController?.pushViewController(vc, animated: true)
        case 4:
            DateSelector.show(self)
        case 6:
            let vc = LB("Common", vcName: "TextInputVC") as! TextInputViewController
            vc.title = "个性签名"
            vc.text = userSign
            vc.placeHolder = "请输入个性签名"
            self.navigationController?.pushViewController(vc, animated: true)
            vc.completeBlock = {(text: String) -> Void in
                let params = ["sign": text]
                g_myDataVC.saveProfile(params, success: { (responseObject) -> Void in
                    DataManager.updateLocalUserInfo("sign", value: text)
                    self.sign.text = userSign
                    }) { (error) -> Void in
                }
            }
        default:
            break
        }
    }
    
    override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
        cell.zeroInsets()
    }

    @IBAction func logout(sender: CBButton) {
        let alertView = UIAlertView(title: alertTitle, message: "确定要退出登录吗？", delegate: self, cancelButtonTitle: "取消", otherButtonTitles: "确定")
        alertView.show()
    }
    
    //MARK: - UIAlertViewDelegate
    func alertView(alertView: UIAlertView, didDismissWithButtonIndex buttonIndex: Int) {
        if buttonIndex == 1 {
            let params = ["userId": userId]
            AJNetworkHelper.instance.post("aj_user_logout", parameters: params, success: { (operation: AFHTTPRequestOperation!, error: AnyObject!) -> Void in
                if (operation.responseObject?["returnCode"] as? String == "000000"){
                    DataManager.clearUserInfo()
                    LGLoginViewController.showLoginView()
                } else {
                    CBAlertView.shareInstance().showMsg("退出失败")
                }
                }, failed: { (operation: AFHTTPRequestOperation!, error: NSError!) -> Void in
                }) { () -> Void in
            }
        }
    }
    
    //MARK: - PhotoPickerDelegate
    func photoPicked(image: UIImage, imagePath: String) {
        let params = ["photo": imagePath]
        g_myDataVC.saveProfile(params, success: { (responseObject) -> Void in
            DataManager.updateLocalUserInfo("photo", value: imagePath)
            self.photoView.image = image
            }) { (error) -> Void in
        }
    }
    
    //MARK: - DateSelectorDelegate
    func dateSelected(date: NSDate) {
        print(date)
    }
}
